package com.seo.service.keyword.proxy.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import org.springframework.stereotype.Service;

import com.seo.mapper.keyword.KeywordMapper;
import com.seo.mapper.keyword.proxy.ProxyKeywordMapper;
import com.seo.pojo.ReturnBody;
import com.seo.service.keyword.proxy.sdk.ProxyKeywordService;
import com.seo.service.keyword.sdk.KeywordService;
import com.seo.utils.CommonUtil;
import com.seo.utils.KeyWordsIndex;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service("proxyKeywordService")
public class ProxyKeywordServiceImpl implements ProxyKeywordService {

	private Map<String, ProxyKeywordServiceImpl> proxyKeywordServiceMap = new HashMap<>();

	@Autowired
	private ProxyKeywordMapper proxyKeywordMapper;

	@Resource(name = "keywordService")
	private KeywordService keywordService;
	
	@Autowired
	private KeywordMapper keywordMapper;

	@Value("${keyword.key}")
	private String key;
	@Value("${keyword.shenma.url}")
	private String shenmaUrl;
	@Value("${keyword.so.url}")
	private String soUrl;
	@Value("${keyword.sougou.url}")
	private String sougouUrl;
	@Value("${keyword.baidu.url}")
	private String baiduUrl;

	@PostConstruct
	public void init() {
		log.info("注册代理交叉添加[{}]", "01");
		put("01", this);
	}

	@Override
	public ReturnBody saveProxyKeyWord(Map<String, Object> param, String uploadType) {
		log.info("添加关键词开始--- param={}", param);
		ReturnBody rb = ReturnBody.init();
		if (param == null || param.isEmpty()) {
			return rb.rollback("参数不能为空");
		}
		try {
			rb.run(proxyKeywordServiceMap.get(uploadType).saveKeyWordProxy(param));
			return rb;
		} catch (Exception e) {
			log.info("添加关键词异常--- e={}", e);
			return rb.rollback("关键词域名重复");
		} finally {
			if (!rb.isSuccess()) {
				rb.result();
			}
			log.info("添加关键词结束--- res={}", rb);
		}

	}

	@Override
	public ReturnBody saveProxyKeyWord1(Map<String, Object> param, String uploadType) {
		log.info("添加关键词开始--- param={}", param);
		ReturnBody rb = ReturnBody.init();
		if (param == null || param.isEmpty()) {
			return rb.rollback("参数不能为空");
		}
		try {
			rb.run(proxyKeywordServiceMap.get(uploadType).saveKeyWordProxy1(param));
			return rb;
		} catch (Exception e) {
			log.info("添加关键词异常--- e={}", e);
			return rb.rollback("关键词域名重复");
		} finally {
			if (!rb.isSuccess()) {
				rb.result();
			}
			log.info("添加关键词结束--- res={}", rb);
		}

	}
	
	/**
	 * 代理三方用户添加关键词
	 * 
	 * @param paramparam
	 * @return String
	 */
	public ReturnBody saveKeyWordProxy(Map<String, Object> param) {
		log.info("代理三方用户添加关键词开始--- param={}", param);
		ReturnBody rb = ReturnBody.init();
		@SuppressWarnings("unchecked")
		Map<String, Object> user = (Map<String, Object>) param.get("user");
		String keyWord = param.get("keyWord") + "";
		String domain = param.get("domain") + "";
		String userId = user.get("userId") + "";
		String proxyId = user.get("id") + "";
		String engineCode = param.get("engineCode") + "";
		engineCode = engineCode.substring(0, engineCode.length() - 1);
		if (StringUtils.isEmpty(keyWord) || StringUtils.isEmpty(domain) || StringUtils.isEmpty(userId)
				|| StringUtils.isEmpty(proxyId) || StringUtils.isEmpty(engineCode)) {
			return rb.rollback("参数不能为空");
		}
		rb.run(CommonUtil.isUrlGroup(domain));

		if (!rb.isSuccess()) {
			rb.getResult().setIsRollBack("01");
			return rb;
		}
		rb.run(CommonUtil.isKeywordGroup(keyWord, "\n"));
		if (!rb.isSuccess()) {
			rb.getResult().setIsRollBack("01");
			return rb;
		}
		List<String> domains = rb.getCollection("urlList", String.class);
		String[] engineCodes = engineCode.split(",");
		List<String> keyWordList = rb.getCollection("keywordList", String.class);
		try {
			List<Map<String, Object>> keyWordOffer = keywordService.getKeyWordOffer(keyWordList, "01",
					Integer.parseInt(userId), engineCodes);
			if (keyWordOffer == null || keyWordOffer.size() == 0) {
				return rb.rollback("关键词报价为空");
			}
			List<Map<String, Object>> successList = new ArrayList<>();
			List<Map<String, Object>> failList = new ArrayList<>();
			for (int i = 0; i < engineCodes.length; i++) {
				for (int j = 0; j < domains.size(); j++) {
					for (Map<String, Object> map : keyWordOffer) {
						Map<String, Object> pa = new HashMap<>();
						String price = "";
						String keywordIndex = "";
						String keyWords = "";
						if ("01".equals(engineCodes[i])) {
							pa.put("engineCodes", "百度PC");
							price = map.get("BaiduPc") + "";
							keywordIndex = map.get("BaiduPcI") + "";
							keyWords = map.get("keyWord") + "";
						}
						if ("02".equals(engineCodes[i])) {
							pa.put("engineCodes", "百度移动");
							price = map.get("BaiduMobile") + "";
							keywordIndex = map.get("BaiduMobileI") + "";
							keyWords = map.get("keyWord") + "";
						}
						if ("03".equals(engineCodes[i])) {
							pa.put("engineCodes", "360PC");
							price = map.get("so") + "";
							keywordIndex = map.get("soI") + "";
							keyWords = map.get("keyWord") + "";
						}
						if ("04".equals(engineCodes[i])) {
							pa.put("engineCodes", "360移动");
							price = map.get("so") + "";
							keywordIndex = map.get("soI") + "";
							keyWords = map.get("keyWord") + "";
						}
						if ("05".equals(engineCodes[i])) {
							pa.put("engineCodes", "神马");
							price = map.get("shenma") + "";
							keywordIndex = map.get("shenmaI") + "";
							keyWords = map.get("keyWord") + "";
						}
						if ("06".equals(engineCodes[i])) {
							pa.put("engineCodes", "搜狗pc");
							price = map.get("SogouPc") + "";
							keywordIndex = map.get("SogouPcI") + "";
							keyWords = map.get("keyWord") + "";
						}
						if ("07".equals(engineCodes[i])) {
							pa.put("engineCodes", "搜狗移动");
							price = map.get("SogouMobile") + "";
							keywordIndex = map.get("SogouMobileI") + "";
							keyWords = map.get("keyWord") + "";
						}
						pa.put("price", price);
						pa.put("keywordIndex", keywordIndex);
						pa.put("keyWord", keyWords);
						pa.put("userId", userId);
						pa.put("proxyId", proxyId);
						pa.put("engineCode", engineCodes[i]);
						pa.put("domain", domains.get(j));
						int count = proxyKeywordMapper.getKeyWordProxyNum(pa);
						if(count > 0) {
							failList.add(pa);
							continue;
						}
						proxyKeywordMapper.saveKeyWordProxy(pa);
						successList.add(pa);
					}
				}
			}
			rb.put("successList", successList);
			rb.put("failList", failList);
		} catch (Exception e) {
			log.info("代理三方用户添加关键词异常--- e={}", e);
			return rb.rollback("关键词域名重复");
		}
		return rb.success();
	}

	public void put(String key, ProxyKeywordServiceImpl service) {
		proxyKeywordServiceMap.put(key, service);

	}

	public ReturnBody saveKeyWordProxy1(Map<String, Object> param) {
		log.info("代理三方用户添加关键词开始--- param={}", param);
		ReturnBody rb = ReturnBody.init();
		@SuppressWarnings("unchecked")
		Map<String, Object> user = (Map<String, Object>) param.get("user");
		String keyWord = param.get("keyWord") + "";
		String domain = param.get("domain") + "";
		String userId = user.get("userId") + "";
		String proxyId = user.get("id") + "";
		String engineCode = param.get("engineCode") + "";
		String price1 = param.get("price1") + "";
		String price2 = param.get("price2") + "";
		engineCode = engineCode.substring(0, engineCode.length() - 1);
		if (StringUtils.isEmpty(keyWord) || StringUtils.isEmpty(domain) || StringUtils.isEmpty(userId)
				|| StringUtils.isEmpty(proxyId) || StringUtils.isEmpty(engineCode)) {
			return rb.rollback("参数不能为空");
		}
		rb.run(CommonUtil.isUrlGroup(domain));

		if (!rb.isSuccess()) {
			rb.getResult().setIsRollBack("01");
			return rb;
		}
		rb.run(CommonUtil.isKeywordGroup(keyWord, "\n"));
		if (!rb.isSuccess()) {
			rb.getResult().setIsRollBack("01");
			return rb;
		}
		List<String> domains = rb.getCollection("urlList", String.class);
		String[] engineCodes = engineCode.split(",");
		List<String> keyWordList = rb.getCollection("keywordList", String.class);
		try {
			List<Map<String, Object>> successList = new ArrayList<>();
			List<Map<String, Object>> failList = new ArrayList<>();
			for (int i = 0; i < engineCodes.length; i++) {
				for (int j = 0; j < domains.size(); j++) {
					for (int y = 0; y < keyWordList.size(); y++) {
						String kw = keyWordList.get(y).trim();
						Map<String, Object> pa = new HashMap<>();
						int num = keywordMapper.getkeyWordConfig(kw);
						String price = "";
						if ("01".equals(engineCodes[i])) {
							pa.put("engineCodes", "百度PC");
							if (num != 0) {
								price = price1;
							} else {
								price = price2;
							}
						}
						if ("02".equals(engineCodes[i])) {
							pa.put("engineCodes", "百度移动");
							if (num != 0) {
								price = price1;
							} else {
								price = price2;
							}
						}
						if ("03".equals(engineCodes[i])) {
							pa.put("engineCodes", "360PC");
							if (num != 0) {
								price = price1;
							} else {
								price = price2;
							}
						}
						if ("04".equals(engineCodes[i])) {
							pa.put("engineCodes", "360移动");
							if (num != 0) {
								price = price1;
							} else {
								price = price2;
							}
						}
						if ("05".equals(engineCodes[i])) {
							pa.put("engineCodes", "神马");
							if (num != 0) {
								price = price1;
							} else {
								price = price2;
							}
						}
						if ("06".equals(engineCodes[i])) {
							pa.put("engineCodes", "搜狗pc");
							if (num != 0) {
								price = price1;
							} else {
								price = price2;
							}
						}
						if ("07".equals(engineCodes[i])) {
							pa.put("engineCodes", "搜狗移动");
							if (num != 0) {
								price = price1;
							} else {
								price = price2;
							}
						}
						pa.put("price", price);
						pa.put("keywordIndex", KeyWordsIndex.getKeyWordsInde(kw, key, engineCodes[i]));
						pa.put("keyWord", kw);
						pa.put("userId", userId);
						pa.put("proxyId", proxyId);
						pa.put("engineCode", engineCodes[i]);
						pa.put("domain", domains.get(j));
						int count = proxyKeywordMapper.getKeyWordProxyNum(pa);
						if(count > 0) {
							failList.add(pa);
							continue;
						}
						proxyKeywordMapper.saveKeyWordProxy(pa);
						successList.add(pa);
					}
				}
			}
			rb.put("successList", successList);
			rb.put("failList", failList);
		} catch (Exception e) {
			log.info("代理三方用户添加关键词异常--- e={}", e);
			return rb.rollback("关键词域名重复");
		}
		return rb.success();
	}
}